package com.sx.pipeline.ui.workbench

import android.app.Application
import android.view.View
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.sx.mvvmlibs.base.BaseViewModel
import com.sx.mvvmlibs.event.SingleLiveEvent
import com.sx.mvvmlibs.http.CommonObserver
import com.sx.mvvmlibs.utils.Logs
import com.sx.mvvmlibs.utils.RxThreadHelper
import com.sx.pipeline.R
import com.sx.pipeline.app.config.AppConstants
import com.sx.pipeline.app.config.CommonApplyType
import com.sx.pipeline.app.config.NewsQuantityType
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.repos.http.req.MessageDTO
import com.sx.pipeline.repos.http.res.*
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.observers.DisposableObserver
import io.reactivex.rxjava3.schedulers.Schedulers

/**
 * @Author: YY
 * @Date: 2022/4/13
 * @Desc: TODO
 */
class WorkBenchVM(app: Application): CYBaseViewModel(app) {

    fun getTaskTabsList(): List<String> {
        val tabs = mutableListOf<String>()
        tabs.add(getApplication<Application>().getString(R.string.my_task))
        tabs.add(getApplication<Application>().getString(R.string.txt_team_task))
        return tabs
    }

    // 轮播图列表数据
    val bannerListEvent: SingleLiveEvent<List<BannerVO>> = SingleLiveEvent()
    // 公告列表
    val noticeListEvent: SingleLiveEvent<List<NoticeBean>> = SingleLiveEvent()
    // 常用应用列表
    val commonApplyEvent: SingleLiveEvent<List<CommonApplyListVO>> = SingleLiveEvent()
    // 未读消息数量
    val noticeQtyEvent: SingleLiveEvent<Int> = SingleLiveEvent()

    /**
     * 加载缓存数据
     */
    fun loadCacheData() {
        val bannerListObservable = Observable.create<List<BannerVO?>> {
            it.onNext(mModel.getCacheListData(AppConstants.CacheKey.CACHE_HOME_BANNER))
        }.subscribeOn(Schedulers.io())
        val noticeListObservable = Observable.create<List<NoticeBean?>> {
            it.onNext(mModel.getCacheListData(AppConstants.CacheKey.CACHE_NOTICE))
        }.subscribeOn(Schedulers.io())
        val commonApplyListObservable = Observable.create<List<CommonApplyListVO?>> {
            it.onNext(mModel.getCacheListData(AppConstants.CacheKey.CACHE_COMMON_APPLY))
        }.subscribeOn(Schedulers.io())

        addSubscribe(
            Observable.mergeDelayError(
                bannerListObservable,
                noticeListObservable,
                commonApplyListObservable
            ).compose(RxThreadHelper.rxSchedulerHelper())
            .subscribe ({
                if (!it.isNullOrEmpty()) {
                    when (it[0]) {
                        is BannerVO -> {
                            Logs.d("BannerVO ${it.size}")
                            if (!it.isNullOrEmpty()) {
                                val data = it as List<BannerVO>
                                bannerListEvent.postValue(data)
                            }
                        }
                        is NoticeBean -> {
                            Logs.d("NoticeBean ${it.size}")
                            if (!it.isNullOrEmpty()) {
                                val data = it as List<NoticeBean>
                                noticeListEvent.postValue(data)
                            }
                            noticeQtyEvent.postValue(mModel.getNoticeUnreadNum())
                        }
                        is CommonApplyListVO -> {
                            Logs.d("CommonApplyListVO ${it.size}")
                            if (!it.isNullOrEmpty()) {
                                val data = it as List<CommonApplyListVO>
                                updateIcon {newsMap->
                                    var joined= (newsMap[NewsQuantityType.TASK_INVOLVED.code] ?: 0)
                                    var approved= (newsMap[NewsQuantityType.TASK_APPROVED.code] ?: 0)
                                    data.find { CommonApplyType.INVOLVED.jumpLink.equals(it.jumpLink) }?.let {
                                        it.num=joined
                                    }
                                    data.find { CommonApplyType.APPROVED.jumpLink.equals(it.jumpLink) }?.let {
                                        it.num=approved
                                    }
                                    commonApplyEvent.postValue(data)
                                }

                            }
                        }
                    }
                } else {
                    getWorkBenchData()
                }
            }, {
                getWorkBenchData()
            })
        )
    }

    /**
     * 获取数据
     */
    fun getWorkBenchData() {
        val observer: DisposableObserver<*> = object : CommonObserver<Any, BaseViewModel<*>>(
            this, false) {
            override fun onResult(result: Any) {
                if (result is List<*>) {
                    if(!CollectionUtils.isEmpty(result)){
                        when(result[0]) {
                            is BannerVO -> {
                                Logs.d("BannerVO ${result.size}")
                                if (result.isNotEmpty()) {
                                    val data = result as List<BannerVO>
                                    mModel.saveCacheListData(data)
                                    bannerListEvent.postValue(data)
                                }
                            }
                            is CommonApplyListVO -> {
                                Logs.d("CommonApplyListVO ${result.size}")
                                if (result.isNotEmpty()) {
                                    val data = result as List<CommonApplyListVO>
                                    updateIcon {newsMap->
                                        var joined= (newsMap[NewsQuantityType.TASK_INVOLVED.code] ?: 0)
                                        var person= (newsMap[NewsQuantityType.PERSONNEL_AUDIT.code] ?: 0)
                                        var personRecord= (newsMap[NewsQuantityType.REVIEW_SUBMISSION_RECORD.code] ?: 0)
                                        var approved= (newsMap[NewsQuantityType.TASK_APPROVED.code] ?: 0)
                                        data.find { CommonApplyType.INVOLVED.jumpLink.equals(it.jumpLink) }?.let {
                                            it.num=joined
                                        }
                                        data.find { CommonApplyType.APPROVED.jumpLink.equals(it.jumpLink) }?.let {
                                            it.num=approved
                                        }
                                        data.find { CommonApplyType.PERSONNEL_AUDIT.jumpLink.equals(it.jumpLink) }?.let {
                                            it.num=person
                                        }
                                        data.find { CommonApplyType.REVIEW_SUBMISSION_RECORD.jumpLink.equals(it.jumpLink) }?.let {
                                            it.num=personRecord
                                        }
                                        mModel.saveCacheListData(data)
                                        commonApplyEvent.postValue(data)
                                    }

                                }
                            }
                        }
                    }
                } else if (result is InformationVO) {
                    if(!CollectionUtils.isEmpty(result.noticeList)){
                        Logs.d("InformationVO ${result.noticeList[0].noticeTitle} ==== ${result.noticeQty}")
                        mModel.saveCacheListData(result.noticeList)
                        noticeListEvent.postValue(result.noticeList)
                        mModel.setNoticeUnreadNum(result.noticeQty)
                        noticeQtyEvent.postValue(result.noticeQty)
                    }

                }
                mUI.initRefreshEvent().postValue(true)
            }

            override fun onFailed(code: Int, msg: String?) {
                super.onFailed(code, msg)
                mUI.initRefreshEvent().postValue(false)
            }
        }

        addSubscribe(
            Observable.mergeDelayError(
                mModel.getBannerList(),
                mModel.getInformation(),
                mModel.getModuleList()
            )
            .compose(RxThreadHelper.rxSchedulerHelper())
            .subscribeWith(observer as (DisposableObserver<Any>))
        )
    }


    /**
     * 最新供应
     */
    val provideListEvent: SingleLiveEvent<Ipage<ReleaseSupplyVo>?> = SingleLiveEvent()

    fun takePartSupplyList(page: Int) {
        addSubscribe(
            mModel.takePartSupplyList("", page, limit = 10)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Ipage<ReleaseSupplyVo>, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: Ipage<ReleaseSupplyVo>) {
                        provideListEvent.postValue(result)
                        mUI.initRefreshEvent().postValue(true)
                        if (page != 1) {
                            mUI.initLoadEvent().postValue(true)
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        provideListEvent.postValue(null)
                        mUI.initRefreshEvent().postValue(false)
                        if (page != 1) {
                            mUI.initLoadEvent().postValue(false)
                        }
                    }
                })
        )
    }

    /**
     * 最新需求
     */
    val releaseSupplyListEvent: SingleLiveEvent<Ipage<ReleaseNeedsVO>?> = SingleLiveEvent()

    fun takePartNeedPage(page: Int) {
        addSubscribe(
            mModel.takePartNeedPage("",page)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Ipage<ReleaseNeedsVO>, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: Ipage<ReleaseNeedsVO>) {
                        releaseSupplyListEvent.postValue(result)
                        mUI.initRefreshEvent().postValue(true)
                        if (page != 1) {
                            mUI.initLoadEvent().postValue(true)
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        releaseSupplyListEvent.postValue(null)
                        mUI.initRefreshEvent().postValue(false)
                        if (page != 1) {
                            mUI.initLoadEvent().postValue(false)
                        }
                    }
                })
        )

    }

    fun updateIcon(callBaCK:(mutableMap: HashMap<String,Int>)->Unit){
        mModel.getUserInfo()
            .compose(RxThreadHelper.rxSchedulerHelper())
            .subscribeWith(object : CommonObserver<UserInfoVO, BaseViewModel<*>>
                (this, false) {

                override fun onResult(result: UserInfoVO) {
                    callBaCK.invoke(result.newsQuantityMap ?: HashMap())
                }

                override fun onFailed(code: Int, msg: String?) {
                    super.onFailed(code, msg)
                    callBaCK.invoke(HashMap())
                }

                override fun onError(e: Throwable) {
                    super.onError(e)
                    callBaCK.invoke(HashMap())
                }
            })
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        loadCacheData()
        getWorkBenchData()
        LogUtils.i("WorkBenchVM onResume")
    }
}
